package netservice

import (
	"net/url"
	"time"

	"gitee.com/liyp_admin/gnet"
	"github.com/gorilla/websocket"
)

type IOserver struct {
	gnet.STIoservice

	itvList []*gnet.Interval

	TotalBytes int

	beginTime int64
}

var TenSecUpdate float32

func (v *IOserver) OnInit() {
	TenSecUpdate = 10

	v.itvList = make([]*gnet.Interval, 0)
	v.beginTime = time.Now().UnixNano()
	// go func() {
	// 	time.Sleep(1 * time.Second)
	// 	for i := 0; i < 1000; i++ {
	// 		v.Connect("ws://127.0.0.1:10081/ws")

	// 	}
	// }()
}

// func (v *IOserver) OnStop() {
// 	//time.Sleep(1000 * time.Millisecond)
// }

//OnAccept ...
func (v *IOserver) OnAccept(itv *gnet.Interval) {
	v.itvList = append(v.itvList, itv)
	gnet.Warning("connections:%d", len(v.itvList))
}

//OnClose  ...
func (v *IOserver) OnClose(itv *gnet.Interval) {
	for i := 0; i < len(v.itvList); i++ {
		if v.itvList[i].ID == itv.ID {
			v.itvList = append(v.itvList[:i], v.itvList[i+1:]...)
			gnet.Print("remove %d", itv.ID)
			break
		}

	}
}

//OnReceive ...
func (v *IOserver) OnReceive(itv *gnet.Interval, data []byte, isText bool) {

	itv.Send(websocket.BinaryMessage, data)
	v.TotalBytes += len(data)
}

func (v *IOserver) OnConnected(itv *gnet.Interval) {
	// buff := make([]byte, 4096)
	// itv.Send(websocket.BinaryMessage, buff)
}

//OnPingpong ...
func (v *IOserver) OnPingpong(itv *gnet.Interval, tm int64) {
	// println("pingpong:", tm)
}

func (v *IOserver) OnConsoleCMD(cmd string) {
	switch cmd {
	default:
		gnet.Error("无效命令:%s", cmd)
	}
}

//OnUpdate ...
func (v *IOserver) OnUpdate(delta float32) {
	// gnet.Print("OnUpdate")
}

func (v *IOserver) OnLoop() bool {
	// select {
	// case data := <-dbif.ChanSend:
	// 	players.AnalyDBData(data)
	// default:
	// 	return false
	// }
	// if time.Now().UnixNano()-v.beginTime >= 1000000000 {
	// 	gnet.Success("totalsize:%d", v.TotalBytes/2)
	// 	v.TotalBytes = 0
	// 	v.beginTime = time.Now().UnixNano()
	// }
	return true
}

func (v *IOserver) OnRequset(cmd string, Form *url.Values) []byte {
	return []byte("abc")
}

var (
	consoleUpdateTime float32
	curSecond         int64
)

//Start ...
func init() {
	consoleUpdateTime = 0
}
